<?php declare(strict_types=1);


namespace App\Utils;


use App\Constants\CoContext;
use Hyperf\HttpServer\Request;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\Utils\Context;
use Hyperf\Utils\Coroutine;

class Common
{
    /**
     * 生成分布式全局唯一 ID
     * @return int
     */
    public static function generate()
    {
        return di(IdGeneratorInterface::class)->generate();
    }

    /**
     * 获取单次请求的唯一 ID
     * @param int|null $id
     * @return int|null
     */
    public static function getRequestID(int $id = null): ?int
    {
        if (!$id) $id = Coroutine::id();
        $requestID = Context::get(sprintf(CoContext::REQUEST_ID, $id), null, $id);
        return (int)$requestID ?? null;
    }

    /**
     * 设置单次请求的协程上下文唯一 requestID
     * @param int|null $id # 协程 ID
     * @param null $requestID # 全局请求唯一 ID
     * @return mixed
     */
    public static function setRequestID(int $id = null, $requestID = null)
    {
        if (!$id) $id = Coroutine::id();
        if (!$requestID) $requestID = self::generate();
        return Context::set(sprintf(CoContext::REQUEST_ID, $id), $requestID);
    }

    /**
     * @param $platform
     * @return bool
     */
    public static function checkResource($platform){
        $path = di(Request::class)->path();
        [$origin] = explode('/', $path);
        return $origin == $platform;
    }
}